﻿using RXY_Mall.Core;
using RXY_Mall.Data;
using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Linq.Dynamic;
using System.Collections.Generic;
using RXY_Mall.Domain;
using EntityFramework.Extensions;
using EntityFramework.Caching;
using RXY_Mall.Core.Tool;
using RXY_Mall.Services.User;
using RXY_Mall.Services.User.Dto;

namespace RXY_Mall.Services.User
{
    public class UserService : IUserService
    {
        private RXY_MallContext db = new RXY_MallContext();

        public async Task<bool> ExistUserByMobile(string mobile)
        {
            bool flag = false;
            flag = await db.gw_users.AnyAsync(u => u.name == mobile);
            return flag;
        }

        public async Task<ResponseService<bool>> IsUseByUser(int user_id)
        {
            ResponseService<bool> result = new ResponseService<bool>();
            result.data = false;
            var user = await db.gw_users.FindAsync(user_id);
            if (user == null || user.deleted == true)
            {
                result.msg = "该用户不存在";
                return result;
            }

            if (user.status == 0)
            {
                result.msg = "黑名单用户";
                return result;
            }
            result.data = true;
            return result;
        }

        /// <summary>
        /// 验证密码是否正确
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="password"></param>
        /// <param name="password_type"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool IsPassword(int user_id, string password, int password_type, out string error)
        {
            bool flag = false;
            error = "";
            var passwords = db.gw_user_passwords.FirstOrDefault(p => p.user_id == user_id && p.type == password_type);

            if (passwords == null)
            {
                error = "请设置支付密码";
                return flag;
            }

            if (passwords.block_time > DateTime.Now)
            {
                error = "密码输错次数过多，已锁30分钟";
                return flag;
            }

            //记录五次
            if (passwords.password != EncryptionHelper.EncryptText(password))
            {
                var date = DateTime.Now.AddMinutes(-30);
                var count = db.gw_user_password_logs.Count(l => l.user_id == user_id && l.type == password_type && l.add_time > date);
                if (count >= 5)
                {
                    error = "30分钟内密码输出5次锁30分钟";
                    return flag;
                }
                var log = new gw_user_password_log() { add_time = DateTime.Now, user_id = user_id, type = (byte)password_type };
                db.gw_user_password_logs.Add(log);
                db.SaveChanges();
                if (count < 3)
                {
                    error = "支付密码错误";
                }
                else
                {
                    error = string.Format("支付密码输错{0}次", count);
                }

                return flag;
            }
            return true;
        }

        /// <summary>
        /// 所有用户
        /// </summary>
        /// <returns></returns>
        public List<SimpleUser> GetUsers()
        {
            var users = db.gw_users
                    .Select(u => new SimpleUser
                    {
                        id = u.id,
                        logo = u.logo,
                        name = u.name,
                        nick_name = u.nick_name,
                        parent_id = u.parent_id,
                        grade = u.grade,
                    })
                    .FromCache(CachePolicy.WithDurationExpiration(TimeSpan.FromSeconds(60)))
                    .ToList();
            return users;
        }

        /// <summary>
        /// 获得一级粉丝
        /// </summary>
        /// <returns></returns>
        public List<SimpleUser> GetChildren(int user_id)
        {
            var children = GetUsers().Where(u => u.parent_id == user_id).ToList();
            return children;
        }

        /// <summary>
        /// 获得掌门人
        /// </summary>
        /// <returns></returns>
        public SimpleUser GetGuildChief(int user_id)
        {
            var parent = GetUsers().Find(u => u.id == user_id);
            if (parent != null && parent.parent_id != null)
            {
                parent = GetGuildChief((int)parent.parent_id);
            }
            return parent;
        }

        /// <summary>
        /// 批量添加用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseService<UserOutput>> AddUsers(AddUserInput input)
        {
            ResponseService<UserOutput> result = new ResponseService<UserOutput>();
            result.code = 0;
            try
            {
                result.data = new UserOutput();
                result.data.success_users = new List<string>();
                result.data.fail_users = new List<FailUserOutput>();
                var managers = await db.gw_managers.ToListAsync();
                foreach (var item in input.users)
                {
                    var manager = managers.FirstOrDefault(u => u.api_manager_id == item.api_manager_id);
                    if (manager == null)
                    {
                        result.data.fail_users.Add(new FailUserOutput() { api_user_id = item.api_user_id, reason = "推荐人不存在", });
                        continue;
                    }

                    //检查手机号
                    var flag = await db.gw_users.AnyAsync(u => u.name == item.mobile && u.company_id == manager.company_id);
                    if (flag)
                    {
                        result.data.fail_users.Add(new FailUserOutput() { api_user_id = item.api_user_id, reason = "手机号已存在" });
                        continue;
                    }

                    try
                    {
                        //用户
                        var user = new gw_user()
                        {
                            add_time = DateTime.Now,
                            add_ip = DcRequest.GetIP(),
                            nick_name = item.accepter_name,
                            grade = 0,
                            name = item.mobile,
                            sex = "M",
                            status = 1,
                            token = Guid.NewGuid().ToString(),
                            company_id = manager.company_id,
                            api_user_id = item.api_user_id,
                        };
                        db.gw_users.Add(user);

                        //资产
                        gw_finance_property userProperty = new gw_finance_property()
                        {
                            balance = 0,
                            bean = 0,
                            id = user.id,
                            child = 0,
                            exp = 0,
                        };
                        user.gw_finance_property = userProperty;

                        //地址
                        gw_user_address_book address = new gw_user_address_book()
                        {
                            accepter_name = item.accepter_name,
                            country_code = item.country_code,
                            address = item.address,
                            add_time = DateTime.Now,
                            area = item.area,
                            city_code = item.city_code,
                            is_default = true,
                            mobile = item.mobile,
                            province_code = item.province_code,
                        };
                        user.gw_user_address_books.Add(address);

                        //店铺
                        gw_user_store userStore = new gw_user_store()
                        {
                            id = user.id,
                            address = item.address,
                            add_time = DateTime.Now,
                            area = item.area,
                            city_code = item.city_code,
                            contacts_name = item.accepter_name,
                            country_code = item.country_code,
                            is_pass = true,
                            manager_id = manager.id,
                            mobile = item.mobile,
                            name = item.store_name,
                            province_code = item.province_code,
                            type = (byte)item.store_type,
                        };
                        user.gw_user_store = userStore;

                        db.gw_users.Add(user);
                        await db.SaveChangesAsync();
                        result.data.success_users.Add(user.api_user_id);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(ex);
                        result.data.fail_users.Add(new FailUserOutput() { api_user_id = item.api_user_id, reason = ex.Message });
                    }
                }

                result.code = 1;
                result.msg = "添加成功";
                //result.data = true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
            }
            return result;
        }
    }
}
